import gc
import random
import threading
import time,datetime,sys
from selenium import webdriver
import unittest
from pywinauto.application import Application
from psutil import process_iter
from pywinauto import mouse
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import traceback
import tools
from tools import *

class ParametrizedTestCase(unittest.TestCase):
    """ TestCase classes that want to be parametrized should
        inherit from this class.
    """

    def __init__(self, methodName='runTest', param=None):
        super(ParametrizedTestCase, self).__init__(methodName)
        self.param = param

    @staticmethod
    def parametrize(testcase_class, param=None):
        """ Create a suite containing all tests taken from the given
            subclass, passing them the parameter 'param'.
        """
        testloader = unittest.TestLoader()
        testnames = testloader.getTestCaseNames(testcase_class)
        suite = unittest.TestSuite()
        for name in testnames:
            suite.addTest(testcase_class(name, param=param))
        return suite
class Global_Lock:
    sent_pic_lock = threading.Lock()

class invite_business(ParametrizedTestCase):

    def run_start(self, driver, channelShopId):
        self.login_wechat_shop(driver, channelShopId)
        if self.to_optimal_alliance(driver, channelShopId):
            self.to_business_manager(driver, channelShopId)
        else:
            while not self.to_optimal_alliance(driver, channelShopId):
                time.sleep(5)
                send_person_msg('17326075282', channelShopId, '###对比视频号小店ID失败###', '请检查视频号小店扫码使用了正确的微信')
        # 开始执行
        while 1:
            try:
                # 获取当前时间
                currentMinutes = int(datetime.datetime.now().strftime('%M'))
                if currentMinutes % random.randint(2, 10) == 0:
                    self.check_login_status(driver, channelShopId)
                    print("开始获取达人绑定关系数据")
                    self.to_business_manager(driver, channelShopId)
                    shadow_driver = self.switch_shadow(driver, channelShopId)
                    self.get_business_list(shadow_driver, channelShopId)
                # elif currentMinutes % 8 == 0:
                #     while not self.to_optimal_alliance(driver,channelShopId):
                #         self.relogin(driver, channelShopId)
                gc.collect()
                self.add_business_flow(driver, channelShopId)

            except Exception as e:
                print("driver is:%s" % driver)
                gc.collect()
                send_group_msg(channelShopId, "run_start步骤异常", e)
                self.run_start(driver, channelShopId)

    def add_business_flow(self, driver, channelShopId):
        print("start add_business_flow")
        try:
            sx_ret = self.getTask(channelShopId)
            while sx_ret != None:
                if sx_ret['data'] != None:
                    self.g['channelShopId'] = sx_ret['data']['channelShopId']
                    self.g['operatorPhone'] = sx_ret['data']['operatorPhone']
                    self.g['videoNumberId'] = sx_ret['data']['videoNumberId']
                    self.g['businessCode'] = sx_ret['data']['businessCode']
                    self.g['businessName'] = sx_ret['data']['businessName']
                    # if self.to_optimal_alliance(driver, channelShopId):
                    #     self.to_business_manager(driver, channelShopId)
                    #     self.add_business_invite(driver, self.g['videoNumberId'], channelShopId)
                    # else:
                    #     while not self.to_optimal_alliance(driver, channelShopId):
                    #         time.sleep(5)
                    #         send_person_msg('17326075282', channelShopId, '###对比视频号小店ID失败###', '请检查视频号小店扫码使用了正确的微信')
                    # driver.refresh()
                    self.to_business_manager(driver, channelShopId)
                    self.add_business_invite(driver, self.g['videoNumberId'], channelShopId)
                    self.g = {}
                    sx_ret = self.getTask(channelShopId)
                else:
                    break
        except Exception as e:
            send_error_msg(channelShopId, "add_business_flow: ", e)
            driver.refresh()


    def getTask(self, channelShopId):
        print("开始获取新增达人的任务 %s" %channelShopId)
        try:
            sx_ret = RequestsEdit.get(
                url='https://msd.guang.com/client/channels/rpa/query-bindable-account?channelShopId=%s' % channelShopId)
            if sx_ret == None:
                send_error_msg(channelShopId, "获取新增达人的任务", "任务失败，返回结果异常。response：%s" % sx_ret)
                time.sleep(30)
                return sx_ret
            else:
                sx_ret = sx_ret.json()
                assert sx_ret['code'] == 0
                return sx_ret
        except Exception as e:
            send_group_msg("getTask", "getTask异常", e)

    def login_wechat_shop(self, driver, channelShopId):
        # 登录视频号小店
        try:
            print("开始登录视频号小店")
            driver.refresh()
            driver.get("https://channels.weixin.qq.com/shop")
            time.sleep(5)
            driver.maximize_window()
            driver.implicitly_wait(10)
            print("爱逛管理员请扫码")
            # 判断是否需要扫码登录
            if is_element_exist_css(driver, ".login__type__container__scan__qrcode"):
                time.sleep(5)
                wechat_shop_QR_code = driver.find_element(By.CSS_SELECTOR ,".login__type__container__scan__qrcode")
                wechat_shop_QR_code_path = tools.scan_pic_path + 'login_qrcode\\' + 'login_wechat_shop_QR_code' + time.strftime(
                    "%Y-%m-%d-%H_%M_%S", time.localtime(time.time())) + ".png"
                wechat_shop_QR_code.screenshot(wechat_shop_QR_code_path)
                # 发送二维码给对应微信，微信昵称备注为视频号小店id
                time.sleep(2)
                self.sent_pic(channelShopId, wechat_shop_QR_code_path)
                time.sleep(2)
            # 判断是否扫码成功
            pointer = 1
            while 1 == 1:
                if is_element_exist_css(driver, ".can-hover"):
                    break
                else:
                    print("正在等待爱逛管理员请扫码")
                    time.sleep(2)
                    pointer += 1
                    if pointer == 150:
                        self.login_wechat_shop(driver,channelShopId)
            print("登录成功")
        except Exception as e:
            send_group_msg("登录", "login_wechat_shop登录视频号小店", e)
            self.login_wechat_shop(driver, channelShopId)

    def check_login_status(self,driver,channelShopId):
        # check登录状态
        print("开始check_login_status")
        try:
            driver.refresh()
            time.sleep(5)
            if is_element_exist_css(driver, ".can-hover"):
                print("已经是登录状态")
            else:
                if is_element_exist_css(driver, "#body > div > div > div > div > h2 > a"):
                    print("登录态失效，爱逛管理员请扫码")
                    driver.find_element(By.CSS_SELECTOR, "#body > div > div > div > div > h2 > a").click()
                    time.sleep(3)
                    wechat_shop_QR_code = driver.find_element(By.CSS_SELECTOR ,".login__type__container__scan__qrcode")
                    wechat_shop_QR_code_path = tools.scan_pic_path + 'login_qrcode\\' + 'login_wechat_shop_QR_code' + time.strftime(
                        "%Y-%m-%d-%H_%M_%S", time.localtime(time.time())) + ".png"
                    wechat_shop_QR_code.screenshot(wechat_shop_QR_code_path)
                    # 发送二维码给对应微信，微信昵称备注为视频号小店id
                    time.sleep(2)
                    self.sent_pic(channelShopId, wechat_shop_QR_code_path)
                    # 判断是否扫码成功
                    pointer = 1
                    while 1 == 1:
                        if is_element_exist_css(driver, ".can-hover"):
                            break
                        else:
                            print("等待爱逛管理员请扫码")
                            time.sleep(2)
                            pointer += 1
                            if pointer == 150:
                                self.login_wechat_shop(driver,channelShopId)
                    print("扫码登录成功")
                else:
                    driver.refresh()
        except Exception as e:
            send_group_msg("登录", "login_wechat_shop登录视频号小店", e)
            self.login_wechat_shop(driver, channelShopId)

    # 进入优选联盟->店铺管理->基础信息 判断小店信息是否正确
    def to_optimal_alliance(self, driver, channelShopId):
        # return True
        try:
            # 判断是否打开店铺管理二级目录
            print("to_optimal_alliance-》进入优选联盟->店铺管理->基础信息 判断小店信息是否正确")
            if is_element_exist_css(driver, "#menuBar .weui-desktop-menu_:nth-of-type(2) > .weui-desktop-menu__link:nth-of-type(1)"):
                driver.find_element(By.CSS_SELECTOR, "#menuBar .weui-desktop-menu_:nth-of-type(2) > .weui-desktop-menu__link:nth-of-type(1)").click()
            print("打开基础信息")
            # 打开基础信息
            driver.find_element(By.CSS_SELECTOR,
                                "li:nth-of-type(2) > .weui-desktop-sub-menu.weui-desktop-sub-menu__current > li:nth-of-type(1) > .weui-desktop-menu__link  .weui-desktop-menu__name").click()
            # 切换shadow_driver
            shadow_driver = self.switch_shadow(driver, channelShopId)
            # 获取小店id
            print("通过元素获取小店id")
            current_shop_id = shadow_driver.find_element(By.CSS_SELECTOR, "#app > div > div:nth-child(3) > div:nth-child(1) > div > div.loading_content_slot > div:nth-child(2) > div > div.table_wrp > table > tbody > tr:nth-child(1) > td:nth-child(2) > div").text
            print("获取到当前视频号小店id为：%s"% current_shop_id)
            time.sleep(10)
            if channelShopId == current_shop_id:
                return True
            else:
                send_group_msg(channelShopId, "判断小店信息是否正确", "视频号小店ID对应不上")
                return False
        except Exception as e:
            send_group_msg(channelShopId, "判断小店基础信息", e)

    # 进入优选联盟->达人管理
    def to_business_manager(self, driver, channelShopId):
        # 判断是否打开优选联盟二级目录
        print("to_business_manager")
        try:
            if is_element_exist_css(driver, "#menuBar > li:nth-child(10) > span.weui-desktop-menu__link.arrow-up"):
                driver.find_element(By.CSS_SELECTOR, "li:nth-of-type(10) > .weui-desktop-sub-menu.weui-desktop-sub-menu__current > li:nth-of-type(3) > .weui-desktop-menu__link  .weui-desktop-menu__name").click()
            else:
                driver.find_element(By.CSS_SELECTOR, "#menuBar > li:nth-child(10) > span").click()
                time.sleep(1)
                driver.find_element(By.CSS_SELECTOR, "li:nth-of-type(10) > .weui-desktop-sub-menu.weui-desktop-sub-menu__current > li:nth-of-type(3) > .weui-desktop-menu__link  .weui-desktop-menu__name").click()
                time.sleep(3)
        except Exception as e:
            send_error_msg(channelShopId, "进入优选联盟->达人管理", e)


    # 切换shadow-root
    def switch_shadow(self, driver, channelShopId):
        try:
            time.sleep(2)
            # 切换到shadow-root
            shadow_driver = driver.execute_script(
                "return document.querySelector('#js_container_box > div.col_main > div.col_main_inner > div:nth-child(2) > div > micro-app').shadowRoot.children[1]")

            time.sleep(2)
            return shadow_driver
        except Exception as e:
            send_error_msg(channelShopId, "切换shadow-root", e)

    # 新增-搜索达人
    def add_business_invite(self, driver, videoNumberId, channelShopId):
        try:
            time.sleep(2)
            # 切换到shadow-root
            shadow_driver = driver.execute_script(
                "return document.querySelector('#js_container_box > div.col_main > div.col_main_inner > div:nth-child(2) > div > micro-app').shadowRoot.children[1]")

            time.sleep(2)
            shadow_driver.find_element(By.CSS_SELECTOR,
                                     "#app > div.weui-desktop-block > div > div > div.flex.justify-between.items-center > div:nth-child(2) > div > button").click()        # 进入新增弹窗页面
            shadow_driver.find_element(By.CLASS_NAME, "weui-desktop-form__input").send_keys(videoNumberId)
            shadow_driver.find_element(By.CSS_SELECTOR,
                                     "span.weui-desktop-form__input-wrp.weui-desktop-form__input_append-in > span.weui-desktop-form__input-append-in").click()        # check 搜索结果
            time.sleep(2)
            # check 搜索结果
            if self.check_search_result(shadow_driver, videoNumberId):
                # 点击【确定】发起邀请
                shadow_driver.find_element(By.CSS_SELECTOR,
                                         "#app > div:nth-child(4) > div > div > div.v-transfer-dom > div.weui-desktop-dialog__wrp > div > div.weui-desktop-dialog__ft > div > div:nth-child(2) > button").click()
                time.sleep(2)
                # 如果当前的小店状态时【邀请中】
                if shadow_driver.find_element(By.CSS_SELECTOR,"td.weui-desktop-table__tr-border").text.replace('\n','').split('ID ')[1] == videoNumberId and shadow_driver.find_element(By.CSS_SELECTOR, "table.weui-desktop-table__core-table > tbody > tr").text.find("邀请中") != -1:
                    send_bind_account_result(channelShopId, videoNumberId, 2)
                    print("等待同意邀请")
                # 达人视频号id对应不上，或者一天内多次邀请
                else:
                    if self.search_business(shadow_driver, videoNumberId):
                        send_bind_account_result(channelShopId, videoNumberId, 2)
                        print("等待同意邀请%s" % videoNumberId)
                    else:
                        send_group_msg(channelShopId, "添加结果check%s" % videoNumberId, "状态异常")
                        send_bind_account_result(channelShopId, videoNumberId, 5)
                        print("添加结果check， 状态异常")
            # driver = driver.execute_script("return document.querySelector('#app")
            driver.refresh()
        except Exception as e:
            driver.refresh()
            send_group_msg(channelShopId, "新增-搜索达人%s" %videoNumberId, e)
            self.to_business_manager(driver, channelShopId)


    # check 搜索结果
    def check_search_result(self, shadow_driver, videoNumberId):
        # 如果有结果，并且搜索出了视频号小店
        if is_element_exist_css(shadow_driver, "#app > div:nth-child(4) > div > div > div.v-transfer-dom > div.weui-desktop-dialog__wrp > div > div.weui-desktop-dialog__bd > div > div.pman-c > div > div.info-c > div.info-ID"):
            # 如果有结果，并且视频号小店符合预期
            if shadow_driver.find_element(By.CSS_SELECTOR, "#app > div:nth-child(4) > div > div > div.v-transfer-dom > div.weui-desktop-dialog__wrp > div > div.weui-desktop-dialog__bd > div > div.pman-c > div > div.info-c > div.info-ID").text[3:] == videoNumberId:
                # 搜索结果是否有【已添加】字段
                if is_element_exist_css(shadow_driver, "#app > div:nth-child(4) > div > div > div.v-transfer-dom > div.weui-desktop-dialog__wrp > div > div.weui-desktop-dialog__bd > div > div.pman-c > div > div.appendIn"):
                    if shadow_driver.find_element(By.CSS_SELECTOR, "#app > div:nth-child(4) > div > div > div.v-transfer-dom > div.weui-desktop-dialog__wrp > div > div.weui-desktop-dialog__bd > div > div.pman-c > div > div.appendIn").text == '已添加':
                        # 回传消息
                        send_bind_account_result(self.g['channelShopId'], self.g['videoNumberId'], 1)
                        if is_element_exist_css(shadow_driver, "#app > div:nth-child(4) > div > div > div.v-transfer-dom > div.weui-desktop-dialog__wrp > div > div.weui-desktop-dialog__hd > button"):
                            shadow_driver.find_element(By.CSS_SELECTOR, "#app > div:nth-child(4) > div > div > div.v-transfer-dom > div.weui-desktop-dialog__wrp > div > div.weui-desktop-dialog__hd > button").click()
                        return False
                else:
                    return True
            # 如果有结果，但是视频号小店符合预期
            else:
                send_group_msg(self.g['videoNumberId'], "搜索小店结果", "搜索小店结果发现videoNumberId不一致")
                return False
        # 如果没有结果
        elif is_element_exist_css(shadow_driver, "#app > div:nth-child(4) > div > div > div.v-transfer-dom > div.weui-desktop-dialog__wrp > div > div.weui-desktop-dialog__bd > div > div > div:nth-child(2) > div:nth-child(2)"):
            # 微信返回未搜索到
            if shadow_driver.find_element(By.CSS_SELECTOR, "#app > div:nth-child(4) > div > div > div.v-transfer-dom > div.weui-desktop-dialog__wrp > div > div.weui-desktop-dialog__bd > div > div > div:nth-child(2) > div:nth-child(2)").text.find("未搜索到") != -1:
                # 通知达人运营
                send_person_msg(self.g['operatorPhone'], self.g['videoNumberId'], self.g['businessName'], self.g['businessCode'])
                # 回传消息
                send_bind_account_result(self.g['channelShopId'], self.g['videoNumberId'], 5)
                return False
            # 其他异常情况
            else:
                result_msg = shadow_driver.find_element(By.CSS_SELECTOR, "#app > div:nth-child(4) > div > div > div.v-transfer-dom > div.weui-desktop-dialog__wrp > div > div.weui-desktop-dialog__bd > div > div > div:nth-child(2) > div:nth-child(2)").text
                send_group_msg(self.g['videoNumberId'], "搜索小店结果", "搜索小店结果发现不符合预期，返回msg: %s" % result_msg)
                # 回传消息
                send_bind_account_result(self.g['channelShopId'], self.g['videoNumberId'], 5)
                return False
        # 搜索后微信没有任何返回
        else:
            send_group_msg(self.g['videoNumberId'], "搜索小店结果", "搜索后微信没有任何返回")
            # 回传消息
            send_bind_account_result(self.g['channelShopId'], self.g['videoNumberId'], 5)
            return False

    # 搜索视频号id，查看结果是否在邀请中
    def search_business(self, shadow_driver, videoNumberId):
        # 如果有结果，并且搜索出了视频号小店
        time.sleep(1)
        shadow_driver.find_element(By.CSS_SELECTOR, "div.flex.justify-between.items-center > div > div > div.weui-desktop-form__input-area > span.weui-desktop-form__input-wrp.weui-desktop-form__input_append-in > input.weui-desktop-form__input").click()
        shadow_driver.find_element(By.CSS_SELECTOR, "div.flex.justify-between.items-center > div > div > div.weui-desktop-form__input-area > span.weui-desktop-form__input-wrp.weui-desktop-form__input_append-in > input.weui-desktop-form__input").clear()
        shadow_driver.find_element(By.CSS_SELECTOR, "div.flex.justify-between.items-center > div > div > div.weui-desktop-form__input-area > span.weui-desktop-form__input-wrp.weui-desktop-form__input_append-in > input.weui-desktop-form__input").send_keys(videoNumberId)
        shadow_driver.find_element(By.CSS_SELECTOR,
                                   "div.flex.justify-between.items-center > div > div > div.weui-desktop-form__input-area > span.weui-desktop-form__input-wrp.weui-desktop-form__input_append-in > span.weui-desktop-form__input-append-in").click()
        time.sleep(2)
        if is_element_exist_css(shadow_driver, "td.weui-desktop-table__tr-border"):
            if shadow_driver.find_element(By.CSS_SELECTOR, "td.weui-desktop-table__tr-border").text.replace('\n', '').split('ID ')[1] == videoNumberId \
                    and shadow_driver.find_element(By.CSS_SELECTOR, "table.weui-desktop-table__core-table > tbody > tr").text.find("邀请中") != -1:
                return True
            else:
                return False
        else:
            # 回传消息
            send_bind_account_result(self.g['channelShopId'], videoNumberId, 5)
            send_group_msg(videoNumberId, "搜索小店结果check", "搜索后没有结果")
            return False
    # 获取达人列表信息
    def get_business_list(self, shadow_driver, channelShopId):
        # 如果有结果，并且搜索出了视频号小店
        try:
            if is_element_exist_css(shadow_driver, "#app > div.weui-desktop-block > div > div > div.flex.justify-end > div > span.weui-desktop-pagination__nav > span > label:nth-child(1)"):
                shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div.flex.justify-end > div > span.weui-desktop-pagination__nav > span > label:nth-child(1)").click()
                # 点击di一页
                page_ele = shadow_driver.find_element(By.CSS_SELECTOR,
                                           "#app > div.weui-desktop-block > div > div > div.flex.justify-end > div > span.weui-desktop-pagination__nav > span").text
                if page_ele.find("...") != -1:
                        page_count = int(page_ele.split("...")[-1])
                else:
                    page_count = int(page_ele[-1:])
                currentMinutes = int(datetime.datetime.now().strftime('%M'))
                # 每隔50分钟获取列表全部的达人信息
                if currentMinutes != 50:
                    page_count = 3
                print("共计%s页" % page_count)
                for n in range(1, page_count + 1, 1):
                    shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div.flex.justify-end > div > span.weui-desktop-pagination__form > input").click()
                    shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div.flex.justify-end > div > span.weui-desktop-pagination__form > input").clear()
                    shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div.flex.justify-end > div > span.weui-desktop-pagination__form > input").send_keys(n)
                    shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div.flex.justify-end > div > span.weui-desktop-pagination__form > a").click()
                    time.sleep(3)
                    for i in range(1,11,1):
                        if is_element_exist_css(shadow_driver, "table.weui-desktop-table__core-table > tbody > tr:nth-child(%d)" % i):
                            print("开始获取第%d个达人信息" % i)
                            business_detail_list = shadow_driver.find_element(By.CSS_SELECTOR,"table.weui-desktop-table__core-table > tbody > tr:nth-child(%d)" % i).text.replace('ID ', '').replace('-','0').split('\n')
                            #['丁叮当的顽皮幻想', 'sph3WKukTc1bCA6', '¥9.90', '1', '合作中', '合作商品', '结束合作']
                            # 转换gmv为分
                            gmv = business_detail_list[2]
                            if gmv.find('¥') != -1:
                                gmv = int(float(gmv[1:]) * 100)
                            else:
                                gmv = 0
                            # 转换status
                            status_str = business_detail_list[4]
                            if status_str == '邀请中':
                                status = 2
                            elif status_str == '已结束':
                                status = 4
                            elif status_str == '合作中':
                                status = 1
                            elif status_str == '已拒绝':
                                status = 3
                            elif status_str == '已取消邀请':
                                status = 0
                            else:
                                status = 5
                            print("get_business_list:%s" % business_detail_list)
                            send_bind_account_result(channelShopId, business_detail_list[1], status, gmv, int(business_detail_list[3]))
                        else:
                            break
            else:
                for i in range(1, 11, 1):
                    if is_element_exist_css(shadow_driver,
                                            "table.weui-desktop-table__core-table > tbody > tr:nth-child(%d)" % i):
                        print("开始获取第%d个达人信息" % i)
                        business_detail_list = shadow_driver.find_element(By.CSS_SELECTOR,
                                                                          "table.weui-desktop-table__core-table > tbody > tr:nth-child(%d)" % i).text.replace(
                            'ID ', '').replace('-', '0').split('\n')
                        # ['丁叮当的顽皮幻想', 'sph3WKukTc1bCA6', '¥9.90', '1', '合作中', '合作商品', '结束合作']
                        # 转换gmv为分
                        gmv = business_detail_list[2]
                        if gmv.find('¥') != -1:
                            gmv = int(float(gmv[1:]) * 100)
                        else:
                            gmv = 0
                        # 转换status
                        status_str = business_detail_list[4]
                        if status_str == '邀请中':
                            status = 2
                        elif status_str == '已结束':
                            status = 4
                        elif status_str == '合作中':
                            status = 1
                        elif status_str == '已拒绝':
                            status = 3
                        elif status_str == '已取消邀请':
                            status = 0
                        else:
                            status = 5
                        print("get_business_list:%s" % business_detail_list)
                        send_bind_account_result(channelShopId, business_detail_list[1], status, gmv,
                                                 int(business_detail_list[3]))
                    else:
                        break

        except Exception as e:
            send_error_msg(channelShopId, "获取达人列表信息", e)

    # 重新登录
    def relogin(self, driver, channelShopId):
        try:
            # 退出登录
            print("relogin > 重新登录")
            if is_element_exist_css(driver, "#header > div > div > div.header_box_msg > div.header_box_item.personInfo > div"):
                driver.find_element(By.CSS_SELECTOR,
                                    "#header > div > div > div.header_box_msg > div.header_box_item.personInfo > div").click()
                driver.find_element(By.CSS_SELECTOR,
                                "#header > div > div > div.header_box_msg > div.header_box_item.personInfo > div > div > div.info-bounce_bottom > ul > li > i").click()
            time.sleep(1)
            print("爱逛管理员请扫码")
            # 判断是否需要扫码登录
            if is_element_exist_css(driver, ".login__type__container__scan__qrcode"):
                wechat_shop_QR_code = driver.find_element(By.CSS_SELECTOR, ".login__type__container__scan__qrcode")
                wechat_shop_QR_code_path = tools.scan_pic_path + 'login_qrcode\\' + 'login_wechat_shop_QR_code' + time.strftime(
                    "%Y-%m-%d-%H_%M_%S", time.localtime(time.time())) + ".png"
                wechat_shop_QR_code.screenshot(wechat_shop_QR_code_path)
                # 发送二维码给对应微信，微信昵称备注为视频号小店id
                time.sleep(2)
                self.sent_pic(channelShopId, wechat_shop_QR_code_path)
                time.sleep(2)
            # 判断是否扫码成功
            pointer = 1
            while 1 == 1:
                if is_element_exist_css(driver, ".can-hover"):
                    break
                else:
                    print("正在等待爱逛管理员请扫码")
                    time.sleep(2)
                    pointer += 1
                    if pointer == 150:
                        self.login_wechat_shop(driver, channelShopId)
            print("登录成功")
        except Exception as e:
            send_group_msg(channelShopId, "判断小店基础信息", e)

    def get_pid(self):
        PID = process_iter()
        for pid_temp in PID:
            pid_dic = pid_temp.as_dict(attrs=['pid', 'name'])
            if pid_dic['name'] == 'WeChat.exe':
                return pid_dic['pid']
        else:
            return 0
        print()

    # 左键点击某个控件
    def click_one(self, title='', control_type='', button='left', found_index=0, left=10, top=10, times=1):
        """
        :param title: 控件名称
        :param control_type: 控件类型
        :param button: left right middle 对应左、右、中三个键
        :param times: 点击次数
        :param found_index: 选择同名同类型多个控件中的第几个
        :param left: X 正方向修正
        :param top: Y 正方向修正
        :return:
        """
        # 在这里控件名称和类型，可以只选择一个，不过定位精准度不高
        if title == '' and control_type == '':
            raise ValueError('控件名和控件类型不可为空!')
        position = self.win.child_window(title=title, control_type=control_type, found_index=found_index).rectangle()
        for i in range(times):
            mouse.click(button=button, coords=(position.left + left, position.top + top))
            if times > 1:
                time.sleep(0.2)

    def connect_wechat(self):
        try:
            Application(backend='uia').start('C:\Program Files (x86)\Tencent\WeChat\WeChat.exe')
        except Exception as e:
            print()
        PID = self.get_pid()
        if PID == 0:
            print('未检测到微信运行')
            return 0
        else:
            self.app = Application(backend='uia')
            self.app.connect(process=PID)
            self.win = self.app[u'微信']
            print('已建立与微信链接')
        print()

    def sent_pic(self, channelShopId, path):
        name_dict = {'wx0829c079cc4ca92a': '爱逛旗舰店', 'wx035a17f37f622fdd': '爱逛女装专营店', 'wx865aea1241c3073b': '爱逛精选食品专营店', 'wx628fb890065d9bc3': '好生活商城', 'wx586a11c48a39cd71': '爱逛严选', 'wxeac71b9166004333':'爱逛臻选', 'wx3b1f2abf2088321f': '爱逛心选', 'wx9ab16ab3b9c65082': '爱逛优选'}
        # lock = threading.Lock()
        Global_Lock.sent_pic_lock.acquire()
        self.connect_wechat()
        print("开始发送登录二维码给爱逛管理员")
        wx_name = name_dict.get(channelShopId)
        try:
            while 1 == 1:
                if self.win.child_window(title=wx_name, control_type='Text').exists(timeout=1):
                    print("点击管理员昵称")
                    time.sleep(3)
                    self.click_one(title=wx_name, control_type='Text')
                    time.sleep(1)
                    self.click_one(title="发送文件", control_type='Button')
                    print("点击发送文件")
                    time.sleep(1)
                    try:
                        self.win.child_window(title="文件名(N):", class_name='Edit').type_keys(path)
                        print("输入文件名")
                    except Exception as e:
                        print()
                    time.sleep(1)
                    try:
                        self.win.child_window(class_name='Button', title='打开(O)').click_input()
                        print("点击打开")
                    except Exception as e:
                        print()
                    time.sleep(1)
                    self.click_one(title="sendBtn", control_type='Button')
                    print("点击发送")
                    time.sleep(1)
                    break
                else:
                    print("当前界面未找到微信联系人：%s" % wx_name)
                    time.sleep(random.randint(30, 60))
        except Exception as e:
            print(e)
            send_error_msg(channelShopId, "sent_pic", e)
        Global_Lock.sent_pic_lock.release()

    def test_run(self):
        self.g = globals()
        thread = []
        options = Options()
        options.add_argument("--incognito")
        driver_path = "C:\Python\Python38\Scripts\chromedriver.exe"
        driver_path1 = "C:\Python\Python38\Scripts\chromedriver1.exe"
        driver_path2 = "C:\Python\Python38\Scripts\chromedriver2.exe"
        driver_path3 = "C:\Python\Python38\Scripts\chromedriver3.exe"
        # driver_path4 = "C:\Python\Python38\Scripts\chromedriver4.exe"
        # driver_path5 = "C:\Python\Python38\Scripts\chromedriver5.exe"

        driver = webdriver.Chrome(driver_path, options=options)
        driver1 = webdriver.Chrome(driver_path1, options=options)
        driver2 = webdriver.Chrome(driver_path2, options=options)
        driver3 = webdriver.Chrome(driver_path3, options=options)
        # driver4 = webdriver.Chrome(driver_path4, options=options)
        # driver5 = webdriver.Chrome(driver_path5, options=options)
        driver.implicitly_wait(10)
        driver1.implicitly_wait(10)
        driver2.implicitly_wait(10)
        driver3.implicitly_wait(10)
        # driver4.implicitly_wait(10)
        # driver5.implicitly_wait(10)

        # 扫码登录必须按照对应关系，顺序：{'爱逛旗舰店', '爱逛女装专营店', '爱逛精选食品专营店',  '好生活商城', '爱逛严选','爱逛臻选'}
        # channelShopIdList = ["wx0829c079cc4ca92a", "wx035a17f37f622fdd", "wx865aea1241c3073b", "wx628fb890065d9bc3", "wx586a11c48a39cd71", "wxeac71b9166004333"]
        # channelShopIdList = ["wx0829c079cc4ca92a", "wx035a17f37f622fdd", "wx865aea1241c3073b", "wx9ab16ab3b9c65082"]
        # channelShopIdList = ["wx586a11c48a39cd71"]
        # driverList = [driver, driver1, driver2, driver3, driver4, driver5]
        driverList = [driver, driver1, driver2, driver3]

        # 开始执行
        for channelShopId in tools.channelShopIdList:
            driver = driverList[channelShopIdList.index(channelShopId)]
            # self.g['lock'] = threading.Lock()
            thread.append(threading.Thread(target=self.run_start, args=(driver, channelShopId)))

        for t in thread:
            time.sleep(random.randint(10, 60))
            t.start()

        for t in thread:
            t.join()



    def re_start(self, channelShopId):
        print("开始kill chrome driver，并且重新开始任务")
        options = Options()
        options.add_argument("--incognito")
        driver_path_list = ["C:\Python\Python38\Scripts\chromedriver.exe", "C:\Python\Python38\Scripts\chromedriver1.exe"]
        channelShopIdList = ["wx0829c079cc4ca92a"]
        driver_path = "C:\Python\Python38\Scripts\chromedriver.exe"
        for i in range(0, len(channelShopIdList), 1):
            if channelShopIdList[i] == channelShopId:
                driver_path = driver_path_list[i]
        print("开始重新声明driver")
        driver = webdriver.Chrome(driver_path, options=options)
        print("driver执行完成")
        driver.implicitly_wait(10)
        return driver

